//
//  HMSendStatusController.swift
//  Weibo
//
//  Created by ZhuDong on 16/5/29.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
import SVProgressHUD

class HMSendStatusController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        registeNotification()
        self.view.backgroundColor = UIColor.whiteColor()
        setNavBar()
        setupUI()
        setupToolbar()
        setupPictureView()
        textView.becomeFirstResponder()
    }
    func registeNotification(){
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(HMSendStatusController.keyboardDidChange(_:)), name: UIKeyboardWillChangeFrameNotification, object: nil)

         NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(HMSendStatusController.btnDidClick(_:)), name: emotionBtnDidClick, object: nil)
    }
    func btnDidClick(notify: NSNotification){
        guard let emotion = notify.object as? HMEmotion else{
            return
        }
       textView.insertEmotion(emotion)
    }
    @objc private func keyboardDidChange(notify: NSNotification){
//        print(notify)
//        let time = (notify.userInfo!["UIKeyboardAnimationDurationUserInfoKey"] as! NSNumber).doubleValue
        let keyboardY = (notify.userInfo!["UIKeyboardFrameEndUserInfoKey"] as! NSValue).CGRectValue()
        let offsetY = -ScreenHeigh + keyboardY.origin.y
        toolbar?.snp_updateConstraints(closure: { (make) in
            make.bottom.equalTo(self.view).offset(offsetY)
        })
        self.view.layoutIfNeeded()
    }
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    var toolbar: UIToolbar?
    private func setupToolbar(){
        let tb = UIToolbar()
        toolbar = tb
        view.addSubview(tb)
        tb.snp_makeConstraints { (make) in
            make.left.right.bottom.equalTo(view)
        }
        
        let itemSettings = [["imageName": "compose_toolbar_picture","actionName": "selectPicture"],
                            ["imageName": "compose_mentionbutton_background","actionName": "selectPicture"],
                            ["imageName": "compose_trendbutton_background","actionName": "selectPicture"],
                            ["imageName": "compose_emoticonbutton_background", "actionName": "selectEmoticon"],
                            ["imageName": "compose_add_background","actionName": "selectPicture"]]
        var items: [UIBarButtonItem] = [UIBarButtonItem]()
        for item in itemSettings {
            let imageName = item["imageName"]
            let action = item["actionName"]!
            let barBtn = UIBarButtonItem(title: nil, imageName: imageName, target: self, action: Selector(action))
            items.append(barBtn)
            let space = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: self, action: nil)
            items.append(space)
        }
        items.removeLast()
        tb.items = items
    }
    @objc private func selectPicture(){
        pictureViewController.view.snp_updateConstraints { (make) in
            make.height.equalTo(ScreenHeigh * 2 / 3)
        }
    }
    private let keyboardView = HMKeyboardView()
    @objc private func selectEmoticon(){
        textView.alwaysBounceVertical = true
        textView.inputView = textView.inputView == nil ? keyboardView : nil
        textView.reloadInputViews()
    }
    private func setupUI(){
        self.view.addSubview(textView)
        textView.delegate = self
        let l = UILabel()
        l.text = "在你身边的才是最重要的"
        l.font = UIFont.systemFontOfSize(18)
        l.textColor = UIColor.darkGrayColor()
        textView.addSubview(l)
        l.snp_makeConstraints(closure: { (make) in
            make.top.equalTo(textView).offset(8)
            make.left.equalTo(textView).offset(5)
        })
        placeHolderL = l
        textView.snp_makeConstraints { (make) in
            make.top.right.left.equalTo(view)
            make.height.equalTo(ScreenHeigh / 3)
        }
        
    }
    
    func setNavBar() -> Void {
        let closeBtn = UIBarButtonItem(title: "关闭", imageName: nil, target: self, action: #selector(HMSendStatusController.closeBtnClick))
        navigationItem.leftBarButtonItem = closeBtn
        let sendBtn = rightBarbuttonItem
        navigationItem.rightBarButtonItem = sendBtn
        setTitleView()
    }
    private func setTitleView(){
        let nameL = UILabel(title: nil, font: UIFont.systemFontOfSize(14), textColor: UIColor.lightGrayColor(), align: .Center)
        nameL.text = HMUserAccountViewModel.shareAccountViewModel.userAccount?.name
        let subL = UILabel(title: "发布微博", font: UIFont.systemFontOfSize(17), textColor: UIColor.lightGrayColor(), align: .Center)
        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: 44))
        titleView.addSubview(nameL)
        nameL.snp_makeConstraints { (make) in
            make.left.right.equalTo(titleView)
            make.bottom.equalTo(titleView).offset(-5)
        }
        titleView.addSubview(subL)
        subL.snp_makeConstraints { (make) in
            make.left.right.top.equalTo(titleView)
        }
        navigationItem.titleView = titleView
    }
    private func setupPictureView(){
        self.addChildViewController(pictureViewController)
        self.view.addSubview(pictureViewController.view)
        self.view.bringSubviewToFront(toolbar!)
        pictureViewController.view.snp_makeConstraints { (make) in
            make.top.equalTo(textView.snp_bottom)
            make.left.right.equalTo(self.view)
            make.height.equalTo(0)
        }
    }
    @objc private func sendBtnClick(){
        if let text = textView.text where text.characters.count > 0 {
            textView.resignFirstResponder()
            let images = pictureViewController.images
            NetworkTools.tools.sendStatus(textView.fullText(),images:images, finish: { (responseObject, error) -> (Void) in
                if error != nil{
                    print(error)
                    SVProgressHUD.showErrorWithStatus("发送微博失败")
                    return
                }
                SVProgressHUD.showSuccessWithStatus("发送微博成功")
            })
        }else{
            SVProgressHUD.showErrorWithStatus("请输入微博内容")
        }
    }
    @objc private func closeBtnClick(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    private lazy var rightBarbuttonItem: UIBarButtonItem = {
        let btn = UIButton()
        //设置文案
        btn.setTitle("发送", forState: .Normal)
        //添加点击事件
        btn.addTarget(self, action:#selector(HMSendStatusController.sendBtnClick) , forControlEvents: .TouchUpInside)
        //设置根据内容显示
        //设置文字颜色
        btn.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        btn.setTitleColor(UIColor.darkGrayColor(), forState: .Disabled)
        //设置背景图片
        btn.setBackgroundImage(UIImage(named: "common_button_orange"), forState: .Normal)
        btn.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: .Disabled)
        btn.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), forState: .Highlighted)
        btn.titleLabel?.font = UIFont.systemFontOfSize(14)
        btn.frame = CGRect(x: 0, y: 0, width: 45, height: 30)
        let barButtonItem = UIBarButtonItem(customView: btn)
        
        return barButtonItem
    }()
    var placeHolderL:UILabel?
    
    private let textView: HMTextView = {
      let tv = HMTextView()
        tv.alwaysBounceVertical = true
        tv.keyboardDismissMode = .OnDrag
        tv.font = UIFont.systemFontOfSize(18)
        tv.backgroundColor = UIColor.lightGrayColor()
        
        return tv
    }()
    private let pictureViewController = HMPicturePickerController()
    
    /*
    private let closeBtn:UIBarButtonItem  = {
//        let btn = UIBarButtonItem(title: "关闭", imageName: nil, target: self, action: #selector(HMSendStatusController.closeBtnClick))
        let btn = UIButton()
        return btn
    }()
    */
}
//MARK: UITextViewDelegate
extension HMSendStatusController:UITextViewDelegate{
    func textViewDidChange(textView: UITextView){
        rightBarbuttonItem.enabled = textView.hasText()
        placeHolderL?.hidden = textView.hasText()
    }
}